package com.everflourish.yeah100.act.welcome;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.everflourish.yeah100.R;
import com.everflourish.yeah100.act.base.BaseActivity;
import com.everflourish.yeah100.act.menu.HomeActivity;
import com.everflourish.yeah100.entity.userinfo.LoginInfo;
import com.everflourish.yeah100.http.HttpURL;
import com.everflourish.yeah100.http.LoginAndRegisterRequest;
import com.everflourish.yeah100.ui.dialog.LoadDialog;
import com.everflourish.yeah100.utils.CommonUtil;
import com.everflourish.yeah100.utils.IntentUtil;
import com.everflourish.yeah100.utils.LogUtil;
import com.everflourish.yeah100.utils.MyToast;
import com.everflourish.yeah100.utils.SPUtil;
import com.everflourish.yeah100.utils.Yeah100;
import com.everflourish.yeah100.utils.constant.Constant;
import com.everflourish.yeah100.utils.constant.ResultCode;
import com.everflourish.yeah100.utils.constant.RoleEnum;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 作者：Created by Administrator on 2016/6/2.
 * 时间：2016/6/2
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {

    private LoginAndRegisterRequest mRequest;
    private TextView mLoginTv, mFindPasswordTv, mRegisterTv;
    private EditText mUserNameEt, mUserPasswordEt;
    private TextInputLayout mUserNameTil, mUserPasswordTil;
    private LoadDialog mLoadDialog;
    private SPUtil spUtil;
    private String mUserName, mPassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initData();
        initView();
        configView();
    }

    private void initData() {
        mRequest = LoginAndRegisterRequest.getInstance();
    }

    private void initView() {
        mUserNameTil = (TextInputLayout) findViewById(R.id.login_user_name_til);
        mUserNameEt = (EditText) findViewById(R.id.login_user_name_et);
        mUserPasswordTil = (TextInputLayout) findViewById(R.id.login_user_password_til);
        mUserPasswordEt = (EditText) findViewById(R.id.login_user_password_et);
        mLoginTv = (TextView) findViewById(R.id.login_tv);
        mFindPasswordTv = (TextView) findViewById(R.id.find_password_tv);
        mRegisterTv = (TextView) findViewById(R.id.register_tv);
        mLoginTv.setOnClickListener(this);
        mFindPasswordTv.setOnClickListener(this);
        mRegisterTv.setOnClickListener(this);
    }

    private void configView() {

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mQueue.stop();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login_tv:
                mUserName = mUserNameEt.getText().toString().trim();
                if (TextUtils.isEmpty(mUserName)) {
                    mUserNameTil.setError("请输入账号");
                    return;
                } else {
                    mUserNameTil.setErrorEnabled(false);
                    mUserNameTil.setError(null);
                }
                mPassword = mUserPasswordEt.getText().toString().trim();
                if (TextUtils.isEmpty(mPassword)) {
                    mUserPasswordTil.setError("请输入密码");
                    return;
                } else {
                    mUserPasswordTil.setErrorEnabled(false);
                    mUserPasswordTil.setError(null);
                }
                userLogin(mUserName, CommonUtil.string2MD5(mPassword));
                break;
            case R.id.register_tv:
                IntentUtil.startActivity(LoginActivity.this, RegisterActivity.class);
                break;
            case R.id.find_password_tv:
                IntentUtil.startActivity(LoginActivity.this, FindPasswordActivity.class);
                break;
        }
    }

    /**
     * 登录请求
     *
     * @param userName
     * @param password
     */
    private void userLogin(String userName, String password) {
        mLoadDialog = LoadDialog.show(mContext, null, "登录中...");
        JsonObjectRequest userLoginRequest = mRequest.userLogin(userName,
                password, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        userLoginListener(response);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mRequest.disposeError(mContext, mLoadDialog, error, "登录失败");
                    }
                });
        mQueue.add(userLoginRequest);
    }

    /**
     * 登录监听
     *
     * @param response
     */
    private void userLoginListener(JSONObject response) {
        try {
            Gson gson = new Gson();
            Yeah100.loginInfo = gson.fromJson(response.toString(),
                    LoginInfo.class);
            if (Yeah100.loginInfo == null
                    || Yeah100.loginInfo.resultCode == null) {
                MyToast.showShort(mContext, "登录失败");
                return;
            }
            String resultCode = Yeah100.loginInfo.resultCode;
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                Yeah100.userId = Yeah100.loginInfo.userInfo.id;
                if (Yeah100.loginInfo.userInfo.photoId != null) {
                    Yeah100.userImageUrl = new HttpURL().URL_IMAGE_GET
                            + Yeah100.loginInfo.userInfo.photoId.replace(
                            ".jpg", "");
                    LogUtil.d("头像url" + Yeah100.userImageUrl);
                } else {
                    Yeah100.userImageUrl = "";
                }
                if (Yeah100.isActivated()) {
                    // 设置-是否是老师身份
                    if (!TextUtils.isEmpty(Yeah100.loginInfo.userInfo.lastRole)
                            && Yeah100.loginInfo.userInfo.lastRole
                            .equals(RoleEnum.TEACHER.name)) {
                        Yeah100.mRoleEnum = RoleEnum.TEACHER;
                        IntentUtil.startActivity(LoginActivity.this, HomeActivity.class, true);
                        spUtil = SPUtil.getSharedPreferences(mContext, SPUtil.FILE_NAME);
                        spUtil.putString(SPUtil.USER_NAME, mUserName);
                        spUtil.putString(SPUtil.PASSWORD, CommonUtil.string2MD5(mPassword));
                        if (spUtil.getBoolean(SPUtil.FIRST_LOGIN, true)) {
                            initConfig();
                        }
                    } else {
//                        Yeah100.mRoleEnum = RoleEnum.STUDENT;
                        showConvertRoleDialog();
                    }
                } else {
                    Yeah100.mRoleEnum = RoleEnum.STUDENT;
                    AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                    builder.setMessage("暂不支持学生身份登录，关注易100微信公众号，即可轻松查询考试成绩！");
                    builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.show();
                }
            } else if (resultCode.equals(ResultCode.result_100009E.resultCode)) {// 用户没有激活
//                            resendEmail();
            } else if (resultCode.equals(ResultCode.result_100008E.resultCode)) {
                MyToast.showShort(mContext, R.string.login_02012_100008E);
            } else if (resultCode.equals(ResultCode.result_000001E.resultCode)) {
                MyToast.showShort(mContext, R.string.login_02011_000001E);
            } else if (resultCode.equals(ResultCode.result_100010E.resultCode)) {
                MyToast.showShort(mContext, R.string.login_02014_100010E);
            } else if (resultCode
                    .equals(ResultCode.result_system_exception_999999E.resultCode)) {
                MyToast.showShort(mContext, R.string.login_020199_999999E);
            } else {
                MyToast.showShort(mContext, R.string.login_020199_999999E);
            }
        } catch (Exception e) {
            MyToast.showShort(mContext, "登录失败");
            LogUtil.e("json异常", e);
        } finally {
            LoadDialog.dismiss(mLoadDialog);
        }
    }

    private void showConvertRoleDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setMessage("暂不支持学生身份登录，是否切换为教师身份登录？");
        builder.setPositiveButton("切换并登录", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                roleUpdateRequest(RoleEnum.TEACHER);
            }
        });
        builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.show();
    }

    /**
     * 切换老师身份登录请求
     *
     * @param roleEnum
     */
    private void roleUpdateRequest(RoleEnum roleEnum) {
        mLoadDialog = LoadDialog.show(mContext, null, "正在切换并登录...");
        JsonObjectRequest request = mRequest.roleUpdateRequest(roleEnum,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        roleUpdateListener(response);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mRequest.disposeError(mContext, mLoadDialog, error, "登录失败");
                    }
                });
        mQueue.add(request);
    }

    /**
     * 切换为老师身份登录监听
     *
     * @param response
     */
    private void roleUpdateListener(JSONObject response) {
        try {
            String resultCode = response
                    .getString(Constant.RESULT_CODE);
            if (resultCode
                    .equals(ResultCode.result_ok.resultCode)) {
                Yeah100.mRoleEnum = RoleEnum.TEACHER;
                IntentUtil.startActivity(LoginActivity.this, HomeActivity.class, true);
                spUtil = SPUtil.getSharedPreferences(mContext, SPUtil.FILE_NAME);
                spUtil.putString(SPUtil.USER_NAME, mUserName);
                spUtil.putString(SPUtil.PASSWORD, CommonUtil.string2MD5(mPassword));
                if (spUtil.getBoolean(SPUtil.FIRST_LOGIN, true)) {
                    initConfig();
                }
            } else {
                MyToast.showLong(mContext, "登录失败");
            }
        } catch (JSONException e1) {
            e1.printStackTrace();
        } finally {
            LoadDialog.dismiss(mLoadDialog);
        }
    }


    /**
     * 初始化配置文件
     */
    private void initConfig() {
        // 设置是否是第一次登录：否
        spUtil.putBoolean(SPUtil.FIRST_LOGIN, false);
        // 设置是静音：是
        spUtil.putBoolean(SPUtil.MUTE, true);
        // 设置是震动：是
        spUtil.putBoolean(SPUtil.VIBRATION, true);
        // 设置是否是老师：是
        // spUtil.putBoolean(SharedPreferencesUtil.IS_CHECKED_TEACHER, true);
    }

}